import { lazyReportCache } from '../utils/report.js'
import { onCachePageshow, getPagePath, isSupportPerformanceObserver } from '../utils/common.js'

/**
 *
 * */
export default function observePaint() {
    if (!isSupportPerformanceObserver()) return
    const entryHandler = (list) => {
        const entries = list.getEntries()
        for (const entry of entries) {
            if (entry.name === 'first-contentful-paint') {
                observer.disconnect()
            }
    
            const json = entry.toJSON()
            Reflect.deleteProperty(json, 'duration')
            const data = {
                type: 'performance',
                subType: entry.name,
                pagePath: getPagePath(),
                ...json,
            }
            lazyReportCache(data)
        }
    }
    
    const observer = new PerformanceObserver(entryHandler)
    observer.observe({ type: 'paint' })
    // 浏览器前进和返回时，需要手动上报
    onCachePageshow(event => {
        requestAnimationFrame(() => {
            ['first-paint', 'first-contentful-paint'].forEach(type => {
                const data = {
                    type: 'performance',
                    subType: type,
                    pagePath: getPagePath(),
                    bfc: true,
                    startTime: performance.now() - event.timeStamp,
                }
                lazyReportCache(data)
            })
        })
    })
}
